package com.lance.core.base;


import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.lance.core.util.ClassUtil;
import com.lance.core.util.JacksonUtil;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.asyncsql.MySQLClient;
import io.vertx.ext.sql.SQLClient;

public class BaseAction extends AbstractVerticle{
	private SQLClient client;
	
	public static final Logger log = LogManager.getLogger();
	
	@Override
	public void start() throws Exception {
		JsonObject mySQLClientConfig = new JsonObject().put("host", "192.168.1.117").put("port", 3306).put("username","root").put("password", "admin").put("database", "dev_epp_web_ctc").put("charset","UTF-8");
		client = MySQLClient.createShared(vertx, mySQLClientConfig);
		EventBus eb = vertx.eventBus();
		Method[] itemMethods = this.getClass().getDeclaredMethods();
		String controllerMappingPath =ClassUtil.captureName(this.getClass().getSimpleName()) ;
		for (Method method : itemMethods) {
			//如果方法为自定义注解且为共有
			VResfulMapping methodMapping = method.getAnnotation(VResfulMapping.class);
			if(null!=methodMapping){
					String messageKey = "/"+controllerMappingPath+"/"+methodMapping.path();
					eb.consumer(messageKey,message ->{
						List<Object> params = new ArrayList<>();
						String msg = (String)message.body();
						params.add(msg);
						params.add(message);
						try {
							method.invoke(this, params.toArray());
						} catch (Exception e) {
							BaseResult br = new BaseResult();
							br.setResultCode(BC.RESULT_ERROR);
							br.setResultMsg(e.getMessage());
							message.reply(JacksonUtil.objectToStr(br));
							log.error("消息订阅异常key=【"+messageKey+"】",e);
						}
					});
			}
		}
	}
	
	public BaseResult success(String resultMsg,Object data){
		AllResult br = new AllResult();
		br.setResultCode(BC.RESULT_SUCCESS);
		br.setResultMsg(resultMsg);
		br.setData(data);
		return br;
	}
	
	public BaseResult success(String resultMsg){
		BaseResult br = new BaseResult();
		br.setResultCode(BC.RESULT_SUCCESS);
		br.setResultMsg(resultMsg);
		return br;
	}
	
	public BaseResult error(String resultMsg,Object data){
		AllResult br = new AllResult();
		br.setResultCode(BC.RESULT_ERROR);
		br.setResultMsg(resultMsg);
		br.setData(data);
		return br;
	}
	
	public BaseResult error(String resultMsg){
		BaseResult br = new BaseResult();
		br.setResultCode(BC.RESULT_ERROR);
		br.setResultMsg(resultMsg);
		return br;
	}
	
	public void response(Message<Object> message,ModelAndView mav){
		message.reply(JacksonUtil.objectToStr(mav));
	}

	public SQLClient getClient() {
		return client;
	}

	public void setClient(SQLClient client) {
		this.client = client;
	}
	
	
	
}
